<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard | MI Tagger</title>
    <link rel="shortcut icon" href="/static/img/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="/static/css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="/static/css/dashboard.css">
    <!-- Java Script -->
    <script type="text/javascript" src="/static/js/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
</head>
<body>
    <div id="header">
        <div id="logo">
            <span style="color: #2aabe2">M</span><span style="color: #ed1b24">I</span>
            <span style="color: #3ab54b">T</span><span style="color: #f6931b">a</span><!--
         --><span style="color: #0072bb">g</span><span style="color: #0171b9">g</span><!--
         --><span style="color: #ed1e79">e</span><span style="color: #2face2">r</span>
        </div> <!-- #logo -->
        <div id="widgets">
            <div id="image-counter">
                Remaining/Total: <span id="remain-images">0</span>/<span id="total-images">0</span>
            </div> <!-- #image-counter -->
        </div> <!-- #widgets -->
        <div id="menu">
            <a href="javascript:void(0)" id="menu-trigger">
                <span class="glyphicon glyphicon-align-justify"></span>
            </a>
            <div id="menu-list">
                <div id="menu-arrow"></div> <!-- #menu-arrow -->
                <ul id="menu-items">
                   <li class="menu-item">
                       <a href="/home/import"><img src="/static/img/icon-photo.png" alt="Upload Image" /> Upload Images</a>
                   </li>
                   <li class="menu-item">
                       <a href="#"><img src="/static/img/icon-article.png" alt="Upload Article" /> Upload Articles</a>
                   </li>
                   <li class="menu-item">
                       <a href="/home/images"><img src="/static/img/icon-image.png" alt="View Image" /> View Images</a>
                   </li> 
                   <li class="menu-item">
                       <a href="#">Help</a>
                   </li> 
                   <li class="menu-item">
                       <a href="/accounts/logout">Log Out</a>
                   </li> 
                </div> <!-- #menu-items -->
            </div> <!-- #menu-list -->
        </div> <!-- #menu-trigger -->
    </div> <!-- #header -->
    <div id="container">
        <div id="workbenches" class="carousel slide" data-ride="carousel" data-interval="false">
            <!-- Wrapper for slides -->
            <div class="carousel-inner">
                <div class="item active">
                    <div class="workbench">
                        <div class="image-title">
                            <h3>Image Title</h3>
                        </div> <!-- .image-title -->
                        <div class="meta-box">
                            <div class="figure-legand">
                                <label for="figure-legand-text">Figure Legend:</label>
                                <textarea class="form-control figure-legand-text" rows="5" readonly></textarea>
                            </div> <!-- .figure-legend -->
                            <div class="image-box">
                                <img class='small-img' src="/static/img/loading.gif" alt="Image" />
                            </div> <!-- .image-box -->
                            <div class="relatived-article">
                                <label for="relatived-article-text">Relevant Article Sentence:</label>
                                <a href="javascript:void(0)" class="upload-relatived-article-trigger">Upload Relevant Article</a>
                                <a href="javascript:void(0)" class="view-relatived-article-trigger">View Relevant Article</a>
                            </div> <!-- .relatived-article -->
                        </div> <!-- .meta-box -->
                        <div class="get-tags-box">
                            <button class="btn btn-recommend">Recommend</button>
                            <button class="btn btn-type">Image Type</button>
                            <button class="btn btn-axes">Axes</button>
                            <input class="text-keyword" type="text">
                            <button class="btn btn-go">Go</Item>
                            <button class="btn btn-search">Search Term</Item>
                        </div> <!-- .get-tags-box -->
                        <div class="tags">
                            <div class="recommend-tags">
                                <div class="label">Recommend</div> <!-- .label -->
                            </div> <!-- .recommend-tags -->
                            <div class="seperator"></div> <!-- .seperator -->
                            <div class="selected-tags">
                                <div class="label">Selected</div> <!-- .label -->
                            </div> <!-- .selected-tags -->
                        </div> <!-- .tags -->
                    </div> <!-- .workbench -->
                </div> <!-- .item -->
            </div> <!-- #workbenches -->
            <!-- Controls -->
            <a class="left carousel-control" href="javascript:void(0)">
                <img src="/static/img/left-trigger.png" alt="Left-Trigger">
            </a>
            <a class="right carousel-control" href="javascript:void(0)">
                <img src="/static/img/right-trigger.png" alt="Right-Trigger">
            </a>
        </div> <!-- #workbenches -->
        
        <input id="article" type="file" accept=".xml" onchange="javascript:uploadArticle(this.files)" />

        <div id="large-image-dialog" class="modal fade" tabindex="-1"> 
            <div class="modal-dialog">
                <div class="modal-body">
                    <img id='large-image' alt='Image' />
                    <button id='close-large-image-dialog' class="btn btn-primary" type="button">Close</button>
                </div> <!-- .modal-body -->
            </div><!-- .modal-dialog -->
        </div><!-- #large-image-dialog -->
        <div id="relatived-article-dialog" class="modal fade" tabindex="-1"> 
            <div class="modal-dialog">
                <div class="modal-body"></div> <!-- .modal-body -->
            </div><!-- .modal-dialog -->
        </div><!-- #relatived-article-dialog -->
        <div id="image-type-dialog" class="modal-dialog hide">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="btn-close close">&times;</button>
                    <h4 class="modal-title">Choose Image Type</h4>
                </div> <!-- .modal-header -->
                <div class="modal-body">
                    <div class="column">
                        <div class="option">
                            <input id="image-type-chart" type="checkbox" value="chart" />
                            <label for="image-type-chart">Chart</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="image-type-timeline" type="checkbox" value="timeline" />
                            <label for="image-type-timeline">Timeline</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="image-type-photograph" type="checkbox" value="photograph" />
                            <label for="image-type-photograph">Photograph</label>
                            <div class="option sub-item">
                                <input id="image-type-portrait" type="checkbox" value="portrait" />
                                <label for="image-type-portrait">Portrait</label>
                            </div> <!-- .option -->
                            <div class="option sub-item">
                                <input id="image-type-patient" type="checkbox" value="patient" />
                                <label for="image-type-patient">Patient</label>
                            </div> <!-- .option -->
                            <div class="option sub-item">
                                <input id="image-type-presentation" type="checkbox" value="presentation" />
                                <label for="image-type-presentation">Presentation</label>
                            </div> <!-- .option -->
                            <div class="option sub-item">
                                <input id="image-type-surgical" type="checkbox" value="surgical" />
                                <label for="image-type-surgical">Surgical</label>
                            </div> <!-- .option -->
                        </div> <!-- .option -->
                    </div> <!-- .column -->
                    <div class="column">
                        <div class="option">
                            <input id="image-type-map" type="checkbox" value="map" />
                            <label for="image-type-map">Map</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="image-type-endoscopic" type="checkbox" value="endoscopic" />
                            <label for="image-type-endoscopic">Endoscopic, Fundocsopic</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="image-type-genetics" type="checkbox" value="genetics" />
                            <label for="image-type-genetics">Genetics</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="image-type-microscopy" type="checkbox" value="microscopy" />
                            <label for="image-type-microscopy">Microscopy</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="image-type-illustration" type="checkbox" value="illustration" />
                            <label for="image-type-illustration">Illustration</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="image-type-diagnostic" type="checkbox" value="diagnostic" />
                            <label for="image-type-diagnostic">Diagnostic Scan</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="image-type-misc" type="checkbox" value="misc" />
                            <label for="image-type-misc">Misc. Image Type</label>
                        </div> <!-- .option -->
                    </div> <!-- .column -->
                </div> <!-- .modal-body -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-default btn-close">Close</button>
                    <button type="button" class="btn btn-primary">Choose types</button>
                </div> <!-- .modal-footer -->
            </div> <!-- .modal-content -->
        </div> <!-- #image-type-dialog -->
        <div id="axes-dialog" class="modal-dialog hide">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="btn-close close">&times;</button>
                    <h4 class="modal-title">Choose Axes</h4>
                </div> <!-- .modal-header -->
                <div class="modal-body">
                    <div class="column">
                        <div class="option">
                            <input id="axes-anatomy" type="checkbox" value="FMA" checked="checked" />
                            <label for="axes-anatomy">Anatomy</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-pathways" type="checkbox" value="PW" checked="checked" />
                            <label for="axes-pathways">Biological Pathways</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-brain" type="checkbox" value="NIFSTD" checked="checked" />
                            <label for="axes-brain">Brain</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-cancer" type="checkbox" value="NCIT" checked="checked" />
                            <label for="axes-cancer">Cancer</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-cells" type="checkbox" value="CL" checked="checked" />
                            <label for="axes-cells">Cells</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-chemicals" type="checkbox" value="CHEBI" checked="checked" />
                            <label for="axes-chemicals">Chemicals</label>
                        </div> <!-- .option -->
                    </div> <!-- .column -->
                    <div class="column">
                        <div class="option">
                            <input id="axes-diseases" type="checkbox" value="DOID" checked="checked" />
                            <label for="axes-diseases">Diseases</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-drugs" type="checkbox" value="RXNORM" checked="checked" />
                            <label for="axes-drugs">Drugs</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-genetics" type="checkbox" value="GO" checked="checked" />
                            <label for="axes-genetics">Genetics</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-imaging" type="checkbox" value="BAO,XCO,FBbi,SNOMEDCT" checked="checked" />
                            <label for="axes-imaging">Imaging</label>
                        </div> <!-- .option -->
                        <div class="option">
                            <input id="axes-proteins" type="checkbox" value="PR" checked="checked" />
                            <label for="axes-proteins">Proteins</label>
                        </div> <!-- .option -->
                    </div> <!-- .column -->
                </div> <!-- .modal-body -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-default btn-close">Close</button>
                    <button type="button" class="btn btn-primary">Choose Axes</button>
                </div> <!-- .modal-footer -->
            </div> <!-- .modal-content -->
        </div> <!-- #axes-dialog -->
        <div id="save-controls">
            <button id="button-finalize" class="btn btn-type">Finalize</button>
            <button id="button-save-xml" class="btn btn-type btn-save">Save as XML</button>
            <button id="button-save-csv" class="btn btn-type btn-save">Save as CSV</button>
            <button id="button-save-both" class="btn btn-type btn-save">Save as Both</button>
            <button id="button-save-all" class="btn btn-type">Save All</button>
        </div> <!-- #save-controls -->
    </div> <!-- #container -->
    <!-- JavaScript -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script type="text/javascript">
        // Global Variables
        window.totalImages  = {{totalImages}};
        window.remainImages = {{remainImages}};
    </script>
    <script type="text/javascript">
        $.fn.hasAttr = function(name) {  
            return this.attr(name) !== undefined;
        };
    </script>
    <script type="text/javascript">
        function getDataForWorkbench(workbenchObject, figureID, offset) {
            $.ajax({
                type: 'GET',
                url: '/home/getImage?figureID=' + figureID + '&offset=' + offset,
                dataType: 'JSON',
                success: function(result){
                    console.log(result);
                    return displayDataForWorkbench(workbenchObject[0], result);
                }
            });
        }
    </script>
    <script type="text/javascript">
        function displayDataForWorkbench(workbenchObject, result) {
            $(workbenchObject).attr('id', 'workbench-' + result['figureID']);

            if ( result['isTitleEmpty'] ) {
                $(workbenchObject).find('.image-title h3').html('[' + result['figureID'] + '] (No Title)');
            } else {
                $(workbenchObject).find('.image-title h3').html('[' + result['figureID'] + '] ' + result['figureTitle']);
            }
            if ( result['isLegendEmpty'] ) {
                $(workbenchObject).find('.figure-legand-text').html('(No Figure Legend)');
            } else {
                $(workbenchObject).find('.figure-legand-text').html(result['figureLegend']);
            }
            if ( !result['isImageExists'] ) {
                $(workbenchObject).find('.image-box').html('(No Image)');
            } else {
                var imageFileLocation = '/' + result['figureFilePath'].replace('uploads/', 'static/');
                $(workbenchObject).find('.image-box').html('<img src="' + imageFileLocation + '" alt="Image">' +
                    '<a href="' + result['figureUrl'] + '" target="_blank">Image Link</a>');
            }
            if ( result['tags'].length == 0 ) {
                $(workbenchObject).find('.recommend-tags').html('<div class="label">Recommend</div>');
                $(workbenchObject).find('.selected-tags').html('<div class="label">Selected</div>');
            } else {
                displayTags(workbenchObject, result['tags']);
            }
        }
    </script>
    <script type="text/javascript">
        function displayTags(workbenchObject, tagList) {
            for ( var i = 0; i < tagList.length; ++ i ) {
                var tagClass = '';
                if ( tagList[i]['tagType'] == 'recommend' ) {
                    tagClass = 'btn-tag';
                } else if ( tagList[i]['tagType'] == 'image-type' ) {
                    tagClass = 'btn-type';
                }

                if ( tagList[i]['isSelected'] ) {
                    if ( $(workbenchObject).find('.selected-tags').find('#ontology-' + tagList[i]['ontologyID']).length != 0 ) {
                        $(workbenchObject).find('.selected-tags').find('#ontology-' + tagList[i]['ontologyID']).append(getSelectedTag(tagList[i]['tagID'], tagList[i]['tagName'], tagList[i]['ontologyName'], tagClass));
                    } else {
                        $(workbenchObject).find('.selected-tags').append(createNewOntologyNode(tagList[i]['ontologyID'], tagList[i]['ontologyName'], '.selected-tags'));
                        $(workbenchObject).find('.selected-tags').find('#ontology-' + tagList[i]['ontologyID']).append(getSelectedTag(tagList[i]['tagID'], tagList[i]['tagName'], tagList[i]['ontologyName'], tagClass));
                    }
                } else {
                    if ( $(workbenchObject).find('.recommend-tags').find('#ontology-' + tagList[i]['ontologyID']).length != 0 ) {
                        $(workbenchObject).find('.recommend-tags').find('#ontology-' + tagList[i]['ontologyID']).append(getRecommendTag(tagList[i]['tagID'], tagList[i]['tagName'], tagList[i]['ontologyName'], tagClass) );
                    } else {
                        $(workbenchObject).find('.recommend-tags').append(createNewOntologyNode(tagList[i]['ontologyID'], tagList[i]['ontologyName'], 'recommend-tags'));
                        $(workbenchObject).find('.recommend-tags').find('#ontology-' + tagList[i]['ontologyID']).append(getRecommendTag(tagList[i]['tagID'], tagList[i]['tagName'], tagList[i]['ontologyName'], tagClass));
                    }
                }
            }
        }
    </script>
    <script type="text/javascript">
    function createNewOntologyNode(ontologyID, ontologyName, place){
        return '<button class="btn btn-ontology btn-ontology-' + ontologyID + '" ontology-id="' + ontologyID + '">' +
                    ontologyName + 
               '</button> ' + 
               '<div id="ontology-' + ontologyID + '" class="ontology" ontology-id="' + ontologyID +'"></div>';
    }
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.btn-ontology', 'click', function() {
            var ontologyID      = $(this).attr('ontology-id'),
                ontologyObject  = $(this).parent().find('#ontology-' + ontologyID);

            $(ontologyObject).toggle();
        });
    </script>
    <script type="text/javascript">
        function getSelectedTag(tagID, tagName, ontologyName, tagClass) {
            if ({{ isReviewer }} == 1){
                return '<div id="tag-' + tagID + '" class="tag">' + 
                        '<div class="tag-name">' +
                            '<button disabled="disabled" class="btn ' + tagClass + '" title="' + tagName + '">' + tagName + '</button>' +
                        '</div> <!-- .tag-name -->' +
                        '<div class="tag-control">' +
                            '<button disabled="disabled" class="btn" ' +
                                    'onclick="javascript:removeSelectedTag(this, ' + tagID + ')">-</button>' +
                        '</div> <!-- .tag-control -->' +
                    '</div>';
            }else{
                return '<div id="tag-' + tagID + '" class="tag">' + 
                        '<div class="tag-name">' +
                            '<button class="btn ' + tagClass + '" title="' + tagName + '">' + tagName + '</button>' +
                        '</div> <!-- .tag-name -->' +
                        '<div class="tag-control">' +
                            '<button class="btn" ' +
                                    'onclick="javascript:removeSelectedTag(this, ' + tagID + ')">-</button>' +
                        '</div> <!-- .tag-control -->' +
                    '</div>';
            }
            
        }
    </script>
    <script type="text/javascript">
        function getRecommendTag(tagID, tagName, ontologyName, tagClass) {
            if ({{ isReviewer }}){
                return '<div id="tag-' + tagID + '" class="tag">' + 
                        '<div class="tag-name">' +
                            '<button disabled="disabled" class="btn ' + tagClass + '" title="' + tagName + '">' + tagName + '</button>' +
                        '</div> <!-- .tag-name -->' +
                        '<div class="tag-control">' +
                            '<button disabled="disabled" class="btn" ' +
                                    'onclick="javascript:addSelectedTag(this, ' + tagID + ')">+</button>' +
                            '<button disabled="disabled" class="btn" ' +
                                    'onclick="javascript:removeRecommendTag(this, ' + tagID + ')">-</button>' +
                        '</div> <!-- .tag-control -->' +
                    '</div>';
            }else{
                return '<div id="tag-' + tagID + '" class="tag">' + 
                        '<div class="tag-name">' +
                            '<button class="btn ' + tagClass + '" title="' + tagName + '">' + tagName + '</button>' +
                        '</div> <!-- .tag-name -->' +
                        '<div class="tag-control">' +
                            '<button class="btn" ' +
                                    'onclick="javascript:addSelectedTag(this, ' + tagID + ')">+</button>' +
                            '<button class="btn" ' +
                                    'onclick="javascript:removeRecommendTag(this, ' + tagID + ')">-</button>' +
                        '</div> <!-- .tag-control -->' +
                    '</div>';
            }
        }
    </script>
    <script type="text/javascript">
    function disableButtons () {
        $('button.btn-recommend').addClass('disabled');
        $('button.btn-type').addClass('disabled');
        $('button.btn-axes').addClass('disabled');
        $('button.btn-go').addClass('disabled');
        $('button.btn-search').addClass('disabled');
    }
    </script>
    <script type="text/javascript">
        $(document).ready(function() {
            var workbenchObject = $('.carousel-inner .item');
            workbenchObject.clone().prependTo('#workbenches .carousel-inner').removeClass('active');
            workbenchObject.clone().appendTo('#workbenches .carousel-inner').removeClass('active');

            $('.workbench').each(function(index) {
                var figureID = {{ figureID }},
                    offset   = index - 1;
                
                getDataForWorkbench( $(this), figureID, offset );
            });

            $('#remain-images').html(window.remainImages);
            $('#total-images').html(window.totalImages);
            if( {{ isReviewer }}){
                disableButtons();
            }
        });
    </script>
    <script type="text/javascript">
        $('.carousel-control').click(function(event) {
            $('.carousel').carousel('pause');

            if ( $(this).hasAttr('disabled') ) {
                event.preventDefault();
                return;
            } 
            resetOntologies();

            $('#button-finalize').html('Finalize');
            $('#button-finalize').removeAttr('disabled');
        });
    </script>
    <script type="text/javascript">
        function disableControl(controlObject) {
            $(controlObject).attr('disabled', 'disabled');
            setTimeout(function() { 
                $(controlObject).removeAttr('disabled');
            }, 1000);
        }
    </script>
    <script type="text/javascript">
        $('.carousel-control.left').click(function(event) {
            if ( $(this).hasAttr('disabled') ) {
                event.preventDefault();
                return;
            } else {
                disableControl( $(this) );
                $('.carousel').carousel('prev');
            }

            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                workbenchObject             = $(currentWorkbenchContainer).next().children('.workbench');

            if ( workbenchObject.length == 0 ) {
                workbenchObject             = $('.item').first().children('.workbench');
            }
            var figureID    = currentWorkbench.attr('id').substr(10),
                offset      = -2;
            console.log(figureID)
            return getDataForWorkbench(workbenchObject, figureID, offset);
        });
    </script>
    <script type="text/javascript">
        $('.carousel-control.right').click(function(event) {
            if ( $(this).hasAttr('disabled') ) {
                event.preventDefault();
                return;
            } else {
                disableControl( $(this) );
                $('.carousel').carousel('next');
            }
            
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                workbenchObject             = $(currentWorkbenchContainer).prev().children('.workbench');

            if ( workbenchObject.length == 0 ) {
                workbenchObject             = $('.item').last().children('.workbench');
            }
            var figureID    = currentWorkbench.attr('id').substr(10),
                offset      = 2;

            return getDataForWorkbench(workbenchObject, figureID, offset);
        });
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.workbench img', 'click', function() {
            var imageUrl = $(this).attr('src');
            $('#large-image').attr('src', imageUrl);
            $('#large-image-dialog').modal('show');
        });
    </script>
    <script type="text/javascript">
        $('#close-large-image-dialog').click(function() {
            $('#large-image-dialog').modal('hide');
        });
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.workbench .upload-relatived-article-trigger', 'click', function() {
            var articleUploadControl  = document.getElementById('article');
            return articleUploadControl.click();
        });
    </script>
    <script type="text/javascript">
        function uploadArticle(files) {
            var articleUploadControl    = document.getElementById('article'),
                formData                = new FormData();

            for ( var i = 0; i < files.length; ++ i ) {
                file = articleUploadControl.files[i];
                formData.append('file_upload', file);
            }
            return uploadFiles(formData);
        }
    </script>
    <script type="text/javascript">;
        function uploadFiles(formData) {
            $.ajax({
                url: '/home/uploadRelevantArticle',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(result) {
                }
            });
        }
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.workbench .view-relatived-article-trigger', 'click', function() {
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                figureID                    = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10);

            $.ajax({
                type: 'GET',
                url: '/home/getRelevantArticle?figureID=' + figureID,
                dataType: 'JSON',
                success: function(result){
                    if ( result['isSuccessful'] ) {
                        $('#relatived-article-dialog .modal-body').html(result['article']);
                        $('#relatived-article-dialog').modal('show');
                    }
                }
            });
        });
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.workbench .get-tags-box .btn-recommend', 'click', function() {
                var recommendButtonObject = $(this),
                currentWorkbenchContainer = $('.item.active'),
                currentWorkbench          = $(currentWorkbenchContainer).children('.workbench'),
                figureID                  = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10),
                figureLegend              = $(currentWorkbench).find('.figure-legand-text').html(),
                ontologies                = getOntologies(),
                figureTitle               = $(currentWorkbench).find('.image-title h3').html();

            if ( figureLegend === "(No Figure Legend)" ) {
                alert("The image has no figure legend. Tag will be recommended based on image title.");
                figureLegend = '';
            }

            $(recommendButtonObject).attr('disabled', 'disabled');
            $(recommendButtonObject).html('Recommending...');
            return getTagsByFigureLegend(currentWorkbench, figureID, figureTitle, figureLegend, ontologies, recommendButtonObject);
        });
    </script>
    <script type="text/javascript"> 
        function getTagsByFigureLegend(workbenchObject, figureID, figureTitle, figureLegend, ontologies, recommendButtonObject) {
            $.ajax({
                type: 'GET',
                url: '/home/getTagsByFigureLegend?figureID=' + figureID + '&figureLegend=' + figureLegend + figureTitle + '&ontologies=' + ontologies,
                dataType: 'JSON',
                success: function(result){
                    addTagsToRecommendBox(workbenchObject, result, 'btn-recommend');
                    $(recommendButtonObject).html('Recommend');
                    $(recommendButtonObject).removeAttr('disabled');
                }
            });
        }
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.workbench .get-tags-box .btn-go', 'click', function() {
            var searchButtonObject          = $(this),
                currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                figureID                    = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10),
                figureLegend                = $(currentWorkbench).find('.figure-legand-text').html(),
                ontologies                  = getOntologies();
            
            $(searchButtonObject).attr('disabled', 'disabled');
            return getTagsByGO(currentWorkbench, figureID, figureLegend, ontologies, searchButtonObject);
        });
    </script>
    <script type="text/javascript">
        function getTagsByGO(workbenchObject, figureID, figureLegend, ontologies, searchButtonObject) {
            $.ajax({
                type: 'GET',
                url: '/home/getTagsByGO?figureID=' + figureID + '&keyword=' + figureLegend + '&ontologies=' + ontologies,
                dataType: 'JSON',
                success: function(result){
                    addTagsToRecommendBox(workbenchObject, result, '');
                    $(searchButtonObject).removeAttr('disabled');
                }
            });
        }
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.workbench .get-tags-box .btn-search', 'click', function() {
            var searchButtonObject          = $(this),
                searchTextboxObject         = $(this).parent().children('input[type=text]'),
                currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                figureID                    = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10),
                keyword                     = $(currentWorkbench).find('.text-keyword').val(),
                ontologies                  = getOntologies();
            
            if ( $(searchTextboxObject).val().trim() === "" ) {
                alert("Please enter the keyword.");
                return;
            }

            $(searchTextboxObject).attr('disabled', 'disabled');
            $(searchButtonObject).attr('disabled', 'disabled');
            $(searchButtonObject).html('Searching...');
            return getTagsByKeyword(currentWorkbench, figureID, keyword, ontologies, searchButtonObject, searchTextboxObject);
        });
    </script>
    <script type="text/javascript">
        function getTagsByKeyword(workbenchObject, figureID, keyword, ontologies, searchButtonObject, searchTextboxObject) {
            $.ajax({
                type: 'GET',
                url: '/home/getTagsByKeyword?figureID=' + figureID + '&keyword=' + keyword + '&ontologies=' + ontologies + '&max-level=4',
                dataType: 'JSON',
                success: function(result){
                    addTagsToRecommendBox(workbenchObject, result, '');
                    $(searchButtonObject).html('Search');
                    $(searchButtonObject).removeAttr('disabled');
                    $(searchTextboxObject).val('');
                    $(searchTextboxObject).removeAttr('disabled');
                }
            });
        }
    </script>
    <script type="text/javascript">
        function addTagsToRecommendBox(workbenchObject, tagList, tagClass) {
            for ( var i = 0; i < tagList.length; ++ i ) {
                if ($(workbenchObject).find('.recommend-tags').find('#ontology-'+ tagList[i]['ontologyID']).length == 0 ) {
                    $(workbenchObject).find('.recommend-tags').prepend(createNewOntologyNode(tagList[i]['ontologyID'], tagList[i]['ontologyName'], '.recommend-tags'));
                    $(workbenchObject).find('.recommend-tags').find('#ontology-'+tagList[i]['ontologyID']).prepend(getRecommendTag(tagList[i]['tagID'], tagList[i]['tagName'], tagList[i]['ontologyName'], tagClass));
                } else {
                    $(workbenchObject).find('.recommend-tags').find('#ontology-'+tagList[i]['ontologyID']).prepend(getRecommendTag(tagList[i]['tagID'], tagList[i]['tagName'], tagList[i]['ontologyName'], tagClass));
                }
            }
        }
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.workbench .get-tags-box .btn-type', 'click', function() {
            getSelectedImageTypes();
            $('#image-type-dialog').removeClass('hide');
        });
    </script>
    <script type="text/javascript">
        $('div.option.sub-item').change(function() {
            var parentOption = $(this).parent('').children('input[type=checkbox]');
            $(parentOption[0]).prop('checked', true);
        });
    </script>
    <script type="text/javascript">
        function getSelectedImageTypes() {
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                selectedImageTypes          = $(currentWorkbench).find('.selected-tags .btn-type');

            $('#image-type-dialog input[type=checkbox]').prop('checked', false);
            for ( var i = 0; i < selectedImageTypes.length; ++ i ) {
                var imageTypeName           = $(selectedImageTypes[i]).html().toLowerCase();
                $('input[value=' + imageTypeName + ']').prop('checked', true);
            }
        }
    </script>
    <script type="text/javascript">
        $('#image-type-dialog .btn-primary').click(function() {
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                figureID                    = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10);

            $('#image-type-dialog .option input[type=checkbox]').each(function() {
                if ( $(this).is(':checked') ) {
                    var imageTypeSlug   = $(this).val(),
                        imageTypeLabel  = $(this).parent('div.option').children('label')[0];
                        imageTypeName   = $(imageTypeLabel).text(),
                        tagID           = -1;

                    return addImageType(figureID, imageTypeName);
                }
            });
            $('#image-type-dialog').addClass('hide');
        });
    </script>
    <script type="text/javascript">
        function addImageType(figureID, imageTypeName) {
            var IMAGE_TYPE_ONTOLOGY_ID      = '1',
                currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                selectedImageTypes          = $(currentWorkbench).find('.selected-tags .btn-type'),
                isSelected                  = false;
            for ( var i = 0; i < selectedImageTypes.length; ++ i ) {
                if ( $(selectedImageTypes[i]).html() == imageTypeName ) {
                    isSelected = true;
                    break;
                }
            }
            if ( !isSelected ) {
                $.ajax({
                    type: 'GET',
                    async: false,
                    url: '/home/setImageType?figureID=' + figureID + '&imageTypeName=' + imageTypeName,
                    dataType: 'JSON',
                    success: function(result){
                        if ( result['isSuccessful'] ) {
                            tagID = result['tagID'];
                            if ($(currentWorkbench).find('.selected-tags').find('#ontology-' + IMAGE_TYPE_ONTOLOGY_ID).length!=0){
                                $(currentWorkbench).find('.selected-tags').find('#ontology-' + IMAGE_TYPE_ONTOLOGY_ID).append( getSelectedTag(tagID, imageTypeName, '', 'btn-type') );
                            }
                            else{
                                $(currentWorkbench).find('.selected-tags').append(createNewOntologyNode(IMAGE_TYPE_ONTOLOGY_ID, 'Image Type', '.selected-tags'));
                                $(currentWorkbench).find('.selected-tags').find('#ontology-' + IMAGE_TYPE_ONTOLOGY_ID).append( getSelectedTag(tagID, imageTypeName, '', 'btn-type') );
                            }
                        }
                    }
                });
            }
        }
    </script>
    <script type="text/javascript">
        $('#image-type-dialog .btn-close').click(function() {
            $('#image-type-dialog').addClass('hide');
        });
    </script>
    <script type="text/javascript">
        $('#workbenches').delegate('.workbench .get-tags-box .btn-axes', 'click', function() {
           $('#axes-dialog').removeClass('hide'); 
        });
    </script>
    <script type="text/javascript">
        function resetOntologies() {
            $('#axes-dialog input[type=checkbox]').prop('checked', true);
        }
    </script>
    <script type="text/javascript">
        function getOntologies() {
            var ontologies = '';
            $('#axes-dialog input[type=checkbox]').each(function() {
                if ( $(this).is(':checked') ) {
                    ontologies += $(this).val() + ',';
                }
            });
            return ontologies;
        }
    </script>
    <script type="text/javascript">
        $('#axes-dialog .btn-primary').click(function() {
           $('#axes-dialog').addClass('hide'); 
        });
    </script>
    <script type="text/javascript">
        $('#axes-dialog .btn-close').click(function() {
           $('#axes-dialog').addClass('hide'); 
        });
    </script>
    <script type="text/javascript">
        function removeSelectedTag(tagControlObject, tagID) {
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                figureID                    = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10),
                tagObject                   = $(tagControlObject).parent().parent('.tag'),
                tagName                     = $(tagObject).find('.btn').html(),
                ontologyObject              = $(tagObject).parent(),
                ontologyID                  = $(ontologyObject).attr('ontology-id'),
                ontologyButtonObject        = $(ontologyObject).parent().find('.btn-ontology-' + ontologyID),
                ontologyName                = $(ontologyButtonObject).html(),
                tagClass                    = $(tagObject).find('.btn').attr('class').substr(4);
            $(tagObject).remove();
            if ($(ontologyObject).children().length==0){
                $(ontologyObject).remove();
                $(ontologyButtonObject).remove();
            }
            if ($(currentWorkbench).find('.recommend-tags').find('#ontology-' + ontologyID).length!=0){
                $(currentWorkbench).find('.recommend-tags').find('#ontology-' + ontologyID).prepend( getRecommendTag(tagID, tagName, ontologyName, tagClass) );
            }
            else{
                $(currentWorkbench).find('.recommend-tags').append(createNewOntologyNode(ontologyID, ontologyName, '.recommend-tags'));
                $(currentWorkbench).find('.recommend-tags').find('#ontology-' + ontologyID).prepend(getRecommendTag(tagID, tagName, ontologyName, tagClass));
            }

            $.ajax({
                type: 'GET',
                url: '/home/setTagSelected?figureID=' + figureID + '&tagID=' + tagID + '&isSelected=false',
                dataType: 'JSON',
                success: function(result){
                }
            });
        }
    </script>
    <script type="text/javascript">
        function addSelectedTag(tagControlObject, tagID) {
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                figureID                    = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10),
                tagObject                   = $(tagControlObject).parent().parent('.tag'),
                tagName                     = $(tagObject).find('.btn').html(),
                ontologyObject              = $(tagObject).parent(),
                ontologyID                  = $(ontologyObject).attr('ontology-id'),
                ontologyButtonObject        = $(ontologyObject).parent().find('.btn-ontology-' + ontologyID),
                ontologyName                = $(ontologyButtonObject).html(),
                tagClass                    = $(tagObject).find('.btn').attr('class').substr(4);
            
            $(tagObject).remove();
            if($(ontologyObject).children().length==0){
                $(ontologyButtonObject).remove();
                $(ontologyObject).remove();
            }
            if ($(currentWorkbench).find('.selected-tags').find('#ontology-'+ontologyID).length==0){
                $(currentWorkbench).find('.selected-tags').prepend(createNewOntologyNode(ontologyID, ontologyName, '.selected-tags'));
                $(currentWorkbench).find('.selected-tags').find("#ontology-"+ontologyID).prepend( getSelectedTag(tagID, tagName, ontologyName, tagClass) );
            }
            else{
                $(currentWorkbench).find('.selected-tags').find("#ontology-"+ontologyID).prepend( getSelectedTag(tagID, tagName, ontologyName, tagClass) );
            }

            $.ajax({
                type: 'GET',
                url: '/home/setTagSelected?figureID=' + figureID + '&tagID=' + tagID + '&isSelected=true',
                dataType: 'JSON',
                success: function(result){
                }
            });
        }
    </script>
    <script type="text/javascript">
        function removeRecommendTag(tagControlObject, tagID) {
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                figureID                    = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10),
                tagObject                   = $(tagControlObject).parent().parent('.tag'),
                ontologyName                = $(tagObject).find('.btn').attr('title'),
                ontologyObject              = $(tagObject).parent(),
                ontologyID                  = $(ontologyObject).attr('ontology-id'),
                ontologyButtonObject        = $(ontologyObject).parent().find('.btn-ontology-' + ontologyID),
                ontologyName                = $(ontologyButtonObject).html();
            $.ajax({
                type: 'GET',
                url: '/home/removeTag?figureID=' + figureID + '&tagID=' + tagID,
                dataType: 'JSON',
                success: function(result){
                    $(tagObject).remove();
                    if($(ontologyObject).children().length==0){
                        $(ontologyButtonObject).remove();
                        $(ontologyObject).remove();
                    }
                      
                }
            });
        }
    </script>
    <script type="text/javascript">
        $('#menu-trigger').click(function() {
            var isVisible = $('#menu-list').is(':visible');
            
            if ( !isVisible ) {
                $('#menu-list').slideDown(36);
            } else {
                $('#menu-list').slideUp(36);
            }
        });
    </script>
    <script type="text/javascript">
        $('#button-finalize').click(function() {
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                currentFigureID             = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10),
                previousWorkbench           = getPreviousWorkbenchObject(),
                previousFigureID            = $(previousWorkbench).attr('id').substr(10),
                nextWorkbench               = getNextWorkbenchObject(),
                nextFigureID                = $(nextWorkbench).attr('id').substr(10);

            $('.carousel-control').attr('disabled', 'disabled');
            $('#button-finalize').html('Finalizing');
            $('#button-finalize').attr('disabled', 'disabled');

            $.ajax({
                type: 'GET',
                url: '/home/finalize?figureID=' + currentFigureID,
                dataType: 'JSON',
                success: function(result){
                    if ( !result['isSuccessful'] ) {
                        alert('Cannot finalize this image, please try again.');
                    } else {
                        $('#button-finalize').html('Finalized');

                        if ( currentFigureID == nextFigureID && currentFigureID == previousFigureID ) {
                            alert('You have tagged all images!');
                            return;
                        }
                        $('.carousel-control').removeAttr('disabled');
                        $('.carousel-control.right').click();
                        getDataForWorkbench(currentWorkbench, previousFigureID, 0);
                    }
                }
            });

            if ( window.remainImages > 0 ) {
                $('#remain-images').html(-- window.remainImages);
            }
        });
    </script>
    <script type="text/javascript">
        function getPreviousWorkbenchObject() {
            var TOTAL_WORKBENCHES      = 3,
                workbenchObjects       = $('.workbench'),
                currentWorkbenchIndex  = 0,
                previousWorkbenchIndex = 0;

            workbenchObjects.each(function(index) {
                if ( $(this).parent().hasClass('active') ) {
                    currentWorkbenchIndex  = index;
                    previousWorkbenchIndex = (currentWorkbenchIndex + 2) % TOTAL_WORKBENCHES;
                }
            });

            return workbenchObjects[previousWorkbenchIndex];
        }
    </script>
    <script type="text/javascript">
        function getNextWorkbenchObject() {
            var TOTAL_WORKBENCHES      = 3,
                workbenchObjects       = $('.workbench'),
                currentWorkbenchIndex  = 0,
                nextWorkbenchIndex     = 0;

            workbenchObjects.each(function(index) {
                if ( $(this).parent().hasClass('active') ) {
                    currentWorkbenchIndex  = index;
                    nextWorkbenchIndex = (currentWorkbenchIndex + 1) % TOTAL_WORKBENCHES;
                }
            });

            return workbenchObjects[nextWorkbenchIndex];
        }
    </script>
    <script type="text/javascript">
        $('#button-save-all').click(function() {
            $.ajax({
                type: 'GET',
                url: '/home/exportAll',
                dataType: 'JSON',
                success: function(result){
                    if ( result['isSuccessful'] ) {
                        window.location.href = '/' + result['fileName'].replace('downloads/', 'static/');
                    }
                }
            });
        });
    </script>
    <script type="text/javascript">
        $('.btn-save').click(function() {
            var currentWorkbenchContainer   = $('.item.active'),
                currentWorkbench            = $(currentWorkbenchContainer).children('.workbench'),
                figureID                    = $(currentWorkbenchContainer).find('.workbench').attr('id').substr(10),
                fileType                    = $(this).attr('id').substr(12);

            $.ajax({
                type: 'GET',
                url: '/home/export?figureID=' + figureID + '&fileType=' + fileType,
                dataType: 'JSON',
                success: function(result){
                    if ( result['isSuccessful'] ) {
                        window.location.href = '/' + result['fileName'].replace('downloads/', 'static/');
                    }
                }
            });
        });
    </script>
</body>
</html>
